package main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import Units.Tank;
/**
 * Panel that intereacts with the spawning units
 * @author Justin Yu
 *
 */
public class SpawnPanel extends JFrame {
	Player p;
	Colony c;
	/**
	 * basic constructor
	 * @param player who owns the unit
	 * @param x location to spawn to
	 * @param y location to spawn to
	 * @param mp map being used
	 * @param bm map grid being used
	 * @param px_x not sure
	 * @param px_y not sure
	 */
	public SpawnPanel(Player player, final int x, final int y, final MapPanel mp, final BasicMap bm, final int px_x, final int px_y) {
		super("Spawn");
		
		p = player;

		JPanel pane = new JPanel();
		JButton col = new JButton ("Colony");

		boolean[][] data = p.getFogData(); 

		if(data[x][y])
			pane.add(col);
		else
			pane.add(new JLabel("no options"));
		
		add(pane);
		
		col.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				c = new Colony(x, y, bm, p);
				if(bm.getLand(x, y).getUnit() == null) {
					if(checkCost(c)) {
						bm.getLand(x, y).addColony(c);
						p.getRes().getColonies().getArray().add(c);
						mp.repaint();
					}
				} else
					JOptionPane.showMessageDialog(new JFrame(), "Invalid (occupied)");
				dispose();
			}		
		});
		
		setLocation(px_x, px_y);
		setVisible(true);
		setSize(300, 75);
		
	}
	/**
	 * checks to make sure that sufficient resources are available to build
	 * @param c the colony array for the player
	 * @return is enough?
	 */
	public boolean checkCost(Colony c) {
		int[] res = p.getRes().getArray();
		int[] cost = c.getCost();

		for(int i = 0; i < res.length; i++) {
			if(res[i] < cost[i]) {
				String tech = "";

				if(i==0)
					tech = "wood";
				else if(i==1)
					tech = "metal";
				else if(i==2)
					tech = "food";
				else if(i==3)
					tech = "happiness";
				else if(i==4)
					tech = "research";

				JOptionPane.showMessageDialog(new JFrame(), ("Not enough resources [" +tech +(res[i]-cost[i]) +"]"));
				return false;
			}
			else res[i] -= cost[i];
		}
		p.getRes().synch();
		return true;
	}
}
